import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { observer} from 'mobx-react';
import { Tools } from 'weaver-mobile';
import classnames from 'classnames';
import moment from 'moment';

const getLabel = Tools.getLabel;

@withRouter
@observer
export default class SignBtn extends Component {
    constructor(props){
        super(props);
        this.state = {
            currTime: this.props.store.currTime || moment()
        }
    }

    componentDidMount() {
        this.monitor();
    }
    
    monitor = () => {
        this.timer != null && clearInterval(this.timer);
        this.timer = setInterval(() => {
            const {store: {currTime}} = this.props;
            this.setState({currTime});
        }, 1000);
    };

    componentWillUnmount = () => {
        clearInterval(this.timer);
    }

    onSignClickHandle = () => {
        const {store} = this.props;
        const {hasLocationInfo, selectedSignData, distance, callSign, redirectToOutsideSignApp, outSignValid} = store;
        if(!hasLocationInfo)
            return;

        const {locationcheck, isOutSign = true} = distance || {};
        if(locationcheck && isOutSign && outSignValid){
            redirectToOutsideSignApp();
        }else{
            selectedSignData && callSign(selectedSignData, () => this.props.history.go(-1));
        }
    }

    render() {
        const {currTime} = this.state;
        const {store} = this.props;
        const {distance, outSignValid} = store;
        const {locationcheck, isOutSign = true} = distance || {};
        const className = classnames({
            'btn': true,
            'btn-outside': locationcheck && isOutSign
        });
        let btnLbl = getLabel('500502','打卡');
        if (locationcheck && isOutSign && outSignValid) btnLbl = getLabel('500503','外勤打卡');

        return (
            <div className={className} onClick={this.onSignClickHandle}>
                {`${currTime.format("HH:mm:ss")} ${btnLbl}`}
            </div>
        )
    }
}